<template>
  <TextArea placeholder="请配置公式" allowClear  v-model="innerValue" @click="onClick"
            class="h-flow-formula-input-text" ref="textInput" />
</template>
<script>
import {Input} from 'ant-design-vue';
import {createModelForVue} from '@/utils';

export default {
  name: 'FormulaInput',
  model: createModelForVue(),
  props: {
    value: {
      type: String,
      default: undefined,
    }
  },
  components: {
    TextArea: Input.TextArea,
  },
  data() {
    return {};
  },
  methods: {
    addVariable(variable) {
      this.doInsert(this.createFormulaText(variable));
    },
    addConstant(variable) {
      this.doInsert(this.createConstFormulaText(variable));
    },
    doInsert(str) {
      let temp = this.innerValue;
      if (!temp) temp = '';
      let el = this.$refs.textInput.$el;
      if (!el) return;
      el = el.firstElementChild;
      let selectionStart = el.selectionStart, selectionEnd = el.selectionEnd;

      if (selectionStart === undefined) {
        selectionStart = selectionEnd = temp.length;
      }

      if (this.selectionStart !== undefined) {
        selectionStart = selectionEnd = this.selectionStart;
      }

      this.innerValue = temp.substring(0, selectionStart)
          + str
          + temp.substring(selectionEnd);

      this.$nextTick(() => {
        if (selectionStart === temp.length) {
          this.selectionStart = (this.innerValue || '').length;
        } else {
          this.selectionStart = selectionStart + str.length;
        }
      });
    },
    onClick() {
      this.selectionStart = undefined;
    },
    addAction(action) {
      this.doInsert(action.value);
    },
    createFormulaText(variable) {
      return `{${variable.variableName}:${variable.variableType}:${variable.variableTitle}}`;
    },
    createConstFormulaText(variable) {
      return `[${variable.variableName}:${variable.variableType}:${variable.variableTitle}]`;
    },
  },
  computed: {
    innerValue: {
      get() {
        return this.value;
      },
      set(value) {
        this.$emit('change', value);
      },
    }
  }
};
</script>
<style>
.h-flow-formula-input-text .ant-input-textarea-clear-icon {
  display: none;
}
.h-flow-formula-input-text textarea {
  max-height: 240px;
  min-height: 120px !important;
}
</style>